package com.frp.lib.handler;

import com.frp.lib.client.ClientApi;
import com.frp.lib.message.Message;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by hujianjun on 11/29 0029.
 */
public class ClientHandler extends SimpleChannelInboundHandler<Message> {
    private static Logger logger = LoggerFactory.getLogger(ClientHandler.class);

    private String password;
    private ClientApi clientApi;

    public ClientHandler(String password, ClientApi clientApi) {
        this.password = password;
        this.clientApi = clientApi;
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//        super.exceptionCaught(ctx, cause);
        logger.error("error", cause);
        ctx.close();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        logger.info("connection closed:{}", ctx.channel());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Message msg) throws Exception {
//        logger.info("msg:{}", msg.toString());
        if ( msg instanceof Message.LoginResp) {
            this.processLoginResp(ctx, (Message.LoginResp) msg);
        } else {
            this.clientApi.onMessage(msg);
        }
    }

    private void processLoginResp(ChannelHandlerContext ctx, Message.LoginResp loginResp) {
//        ctx.pipeline().removeLast();
//        ctx.pipeline().removeLast();
//        ctx.pipeline().removeLast();
//
//        ctx.pipeline().get("log");

        this.clientApi.onLoginResp(ctx, loginResp);
    }
}
